//
//  MyNewFirendViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-6.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyNewFirendViewController.h"
#import "MyNewFirendCell.h"
#import "MyFirendData.h"
#import "MyFirendDataManager.h"
#import "UserId.h"
@interface MyNewFirendViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSInteger pages;
}
@property (nonatomic, strong) MyFirendData *addFirendData;
/**
 *  数据显示
 */
@property (strong, nonatomic) IBOutlet UITableView *myNewFirendTableView;
@property (nonatomic, strong) NSMutableArray *firendObjArr;
// 存放好友的uid
@property (nonatomic, strong) NSMutableDictionary *firendUidDic;

@property (nonatomic, strong) NSMutableArray *focusArr;
//@property (nonatomic, strong) NSIndexPath *indexPath;
@end

@implementation MyNewFirendViewController

//- (NSIndexPath *)indexPath{
//    if (_indexPath == nil) {
//        _indexPath = [[NSIndexPath alloc] init];
//    }
//    return _indexPath;
//}

- (NSMutableArray *)focusArr{
    if (_focusArr == nil) {
        self.focusArr = [NSMutableArray array];
    }
    return _focusArr;
}

- (MyFirendData *)addFirendData{
    if (_addFirendData == nil) {
        _addFirendData = [[MyFirendData alloc] init];
    }
    return _addFirendData;
}

- (NSMutableDictionary *)firendUidDic{
    if (_firendUidDic == nil) {
        self.firendUidDic = [NSMutableDictionary dictionary];
    }
    return _firendUidDic;
}

- (NSMutableArray *)firendObjArr{
    if (_firendObjArr == nil) {
        self.firendObjArr = [NSMutableArray array];
    }
    return _firendObjArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myNewFirendTableView.dataSource = self;
    self.myNewFirendTableView.delegate = self;
    [self setNaviBarAttribute];
    pages = 1;
    self.navigationItem.title = @"关注通知";
    self.myNewFirendTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self firendAdd];
    [self.myNewFirendTableView addFooterWithTarget:self action:@selector(firendAdd)];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - tableView的代理方法 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.firendObjArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 54;
    }else{
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellStr = @"cell";
    MyNewFirendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyNewFirendCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyNewFirendCell" owner:self options:nil] firstObject];
        }
    }
    MyFirendData *myfirendData = [self.firendObjArr objectAtIndex:indexPath.row];
    [cell.headerImageView setImageWithURL:[NSURL URLWithString:myfirendData.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    cell.headerImageView.layer.masksToBounds = YES;
    cell.headerImageView.layer.cornerRadius = 2;
    cell.nameLabel.text = myfirendData.username;
    [cell.attentionButtonAction addTarget:self action:@selector(attentionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButtonAction.layer.masksToBounds = YES;
    cell.attentionButtonAction.layer.cornerRadius = 3;
    if ([self.focusArr containsObject:indexPath]) {
        cell.attentionButtonAction.hidden = YES;
    }
    return cell;
}

#pragma mark - 网络数据请求 -
//  获取关注我的好友列表
- (void)firendAdd{
    [self showActionView];
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/byfollowing/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",pages] forKey:@"page"];
    [manager POST:postURL parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        
        if ([statusString isEqualToString:@"0"]) {
            if (pages == 1) {
                [self shouLabel:@"暂无数据"];
            }
            [self.myNewFirendTableView footerEndRefreshing];
        }else{
            NSArray *arr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            if (arr != nil) {
                pages++;
                for (NSDictionary *obj in arr) {
                    MyFirendData *firendData = [[MyFirendData alloc] init];
                    firendData.myuid = [UserId shareUid].uidStr;
                    [firendData setValuesForKeysWithDictionary:obj];
                    [self.firendObjArr addObject:firendData];
                }
                
            }else if ([arr count] < 20){
                [self.myNewFirendTableView footerEndRefreshing];
            }else{
                if (pages > 1) {
                    MyNSLog("无数据");
                }
            }
        }
        MyNSLog("走完了");
        [self hiddenActionView];
        [self.myNewFirendTableView footerEndRefreshing];
        [self.myNewFirendTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}

//  cell中button的执行方法
- (void)attentionButtonAction:(UIButton *)sender{
    MyNewFirendCell *cell = nil;
    UIView  *view = sender.superview;
    for (NSInteger i = 0; i < 1; ) {
        if ([view isKindOfClass:[MyNewFirendCell class]]) {
            cell = (MyNewFirendCell *)view;
            break;
        }else{
            view = view.superview;
        }
    }
    NSIndexPath *index = [self.myNewFirendTableView indexPathForCell:cell];
    [self.focusArr addObject:index];
    self.addFirendData = [self.firendObjArr objectAtIndex:index.row];
    
    
    [self.firendUidDic setValue:self.addFirendData.uid forKey:@"uid"];
    [self attentionSb];
    cell.attentionButtonAction.hidden = YES;
   
}

//  添加关注
- (void)attentionSb{
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/followuser/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [self.firendUidDic setObject:kPlatform forKey:@"platform"];
    [self.firendUidDic setObject:kVersion forKey:@"version"];
    
    MyNSLog("====添加的关注 %@", self.firendUidDic);
    [manager POST:postURL parameters:self.firendUidDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            // 向数据库添加数据
            [[MyFirendDataManager shareInstance] addNewFirendInfo:self.addFirendData];
            // 存放头像
            [[MyFirendDataManager shareInstance] setImagePath:self.addFirendData.avatar withUid:self.addFirendData.uid withMyUid:self.addFirendData.myuid];
            MyNSLog("关注了我了");
        }
        [self.myNewFirendTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
